<template>
	<view class="controlLayout pageBg">
		<custom-nav-bar title="温室"></custom-nav-bar>
		<!-- 环境监测 -->
		<view class="en-content" v-if="status !== 1">
			<view class="title-row">
				<uni-section title="环境监测" type="line" />
			</view>
			<ControlEnvBar></ControlEnvBar>
		</view>

		<!-- 水肥控制 -->
		<view class="fer-content" v-if="status !== 1">
			<view class="title-row">
				<uni-section title="水肥控制" type="line" />
				<view class="history-title">
					<text @click="togDeviceHistory(houseId)">历史数据</text>
				</view>
			</view>
			<uni-card>

				<!-- 第二行：设备状态 -->
				<view class="device-grid">
					<view v-for="device in devices" :key="device.id" class="device-card"
						@click="toggleRow(device.id,device.name)">

						<view class="row-track" :class="{ active: activeId === device.id }">
							<view class="row-content">
								<text class="device-name">{{ device.name }}</text>
								<text class="device-status" :class="statusClass(device.status)">
									{{ statusText(device.status) }}
								</text>
							</view>

							<view class="actions">
								<button class="btn control" @click.stop="gotToFerControl(device.id,device.name)">控制</button>
								<button class="btn strategy" @click.stop="gotToFerStrategy(device.id,device.name)">策略</button>
							</view>

						</view>

					</view>
				</view>

				<!-- <view slot="actions" class="card-actions">
					<view class="card-actions-item" @click="gotToFerControl()">
						<uni-icons type="settings-filled" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">设备控制</text>
					</view>
					<view class="card-actions-item" @click="gotToFerStrategy()">
						<uni-icons type="gear-filled" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">策略设置</text>
					</view>
				</view> -->
			</uni-card>
		</view>

		<!-- 环控管控 -->
		<view class="cn-content" v-if="status !== 1">
			<view class="title-row">
				<uni-section title="环控管控" type="line" />
				<view class="history-title">
					<text @click="togDeviceHistory(houseId)">历史数据</text>
				</view>
			</view>
			<uni-card>
				<view>
					<!-- 权限切换 -->
					<view class="control-mode-panel">
						<!-- <text class="label">当前控制权限：</text> -->
						<uni-segmented-control :values="['智能控制', '远程人工控制', '现场人工控制']" :current="mode"
							@clickItem="onModeChange" styleType="button" activeColor="#4cd964" />
					</view>

					<view class="last-control">
						<view class="line">操作内容：设备[天窗2]操作反馈</view>
						<view class="line">操作详情：天窗2合拢成功，操作人[模型运行]</view>
						<view class="line">操作模式：自动</view>
						<view class="line">操作时间：2025-11-08 17:28:03</view>
						<view class="line">操作人：系统管理员</view>
					</view>

					<view slot="actions" class="card-actions">
						<view class="card-actions-item" @click="gotToDeviceControl()">
							<uni-icons type="settings-filled" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">设备控制列表</text>
						</view>
						<view class="card-actions-item" @click="gotToStrategy()">
							<uni-icons type="gear-filled" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">策略设置</text>
						</view>
					</view>

				</view>

			</uni-card>

		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import ControlEnvBar from '@/components/control-env-bar/control-env-bar.vue'

	const mode = ref(0); // 0: 智能控制, 1: 远程人工, 2: 现场人工
	const items = ['土壤环境', '空气环境', '气象气候', '综合能耗'];
	const current = ref(0);
	const status = ref(0);
	const strategies = ref([{
			name: '温室灌溉策略',
			time: '每天 06:00',
			enabled: true
		},
		{
			name: '施肥计划',
			time: '每周一 08:00',
			enabled: false
		}
	])

	const history = ref([{
			time: '2025-11-07 08:00',
			action: '自动执行施肥计划'
		},
		{
			time: '2025-11-07 09:30',
			action: '人工关闭水泵A'
		}
	])

	const activeId = ref(null)

	function toggleRow(id) {
		activeId.value = activeId.value === id ? null : id
	}


	async function switchControlMode(targetMode) {
		try {
			// const res = await uni.request({
			//   url: '/api/control/switch-mode',
			//   method: 'POST',
			//   data: { mode: targetMode }
			// })
			if (true) {
				mode.value = targetMode
				uni.showToast({
					title: '切换成功',
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: '切换失败',
					icon: 'none'
				})
			}
		} catch (err) {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			})
		}
	}

	function onModeChange(e) {
		const targetMode = e.currentIndex
		const originalMode = mode.value

		if (targetMode === originalMode) return

		mode.value = targetMode // UI立即切换

		uni.showModal({
			title: '确认切换控制权限',
			content: `确定切换为【${modeLabel(targetMode)}】模式？`,
			success: async res => {
				if (res.confirm) {
					await switchControlMode(targetMode)
				} else {
					mode.value = originalMode // 用户取消 → 恢复原来的选中状态
				}
			}
		})
	}


	function modeLabel(index) {
		return ['智能控制', '远程人工控制', '现场人工控制'][index]
	}

	function stopAllStrategies() {
		strategies.value.forEach(s => (s.enabled = false))
		history.value.push({
			time: new Date().toLocaleString(),
			action: '已停止所有策略'
		})
	}

	const sensors = [{
			name: '空气温度',
			value: '23.5°C'
		},
		{
			name: '空气湿度',
			value: '68%'
		},
		{
			name: '土壤温度',
			value: '19.2°C'
		},
		{
			name: '土壤湿度',
			value: '45%'
		},
		{
			name: '光照强度',
			value: '1200 lx'
		},
		{
			name: 'CO₂浓度',
			value: '410 ppm'
		},
		{
			name: 'CO₂浓度',
			value: '410 ppm'
		},
		{
			name: 'CO₂浓度',
			value: '410 ppm'
		}
	]

	const devices = [
	  { id: 1, name: '农高区1号温室水肥机北侧', status: 'running', strategyType: 'ferStrategy' },
	  { id: 2, name: '农高区1号温室水肥机南侧旧', status: 'error', strategyType: 'xinJieFerStrategy' },
	  { id: 3, name: '农高区1号温室水肥机南侧', status: 'stopped', strategyType: 'fertilizerStrategy' }
	]



	function onClickItem(e) {
		if (current.value != e.currentIndex) {
			current.value = e.currentIndex;
		}
	}

	function statusText(status) {
		switch (status) {
			case 'running':
				return '运行中'
			case 'stopped':
				return '已关闭'
			case 'error':
				return '故障'
			default:
				return '未知'
		}
	}

	function statusClass(status) {
		return status
	}

	function onControl(item) {
		console.log('控制', item)
	}

	function onStrategy(item) {
		console.log('策略', item)
	}

	function goToControl(device) {
		uni.navigateTo({
			url: "/pages/control/ferControl/ferControl",
		});
	}

	function togDeviceHistory(houseId) {
		uni.navigateTo({
			url: "/pages/control/deviceHistory/deviceHistory",
		});
	}

	function gotToFerControl(id, name) {
		uni.navigateTo({
			url: `/pages/control/ferControl/ferControl?id=${id}&name=${name}`
		});
	}
	const strategyPageMap = {
		//有人
	  ferStrategy: '/pages/control/ferStrategy/ferStrategy',
	  // 信捷
	  xinJieFerStrategy: '/pages/control/ferStrategy/xinJieFerStrategy',
	  fertilizerStrategy: '/pages/control/ferStrategy/fertilizerStrategy'
	}

	
	function gotToFerStrategy(id, name) {
	  const device = devices.find(d => d.id === id)
	  const page = strategyPageMap[device.strategyType]
	  if (page) {
	    uni.navigateTo({
	      url: `${page}?id=${id}&name=${name}`
	    })
	  } else {
	    uni.showToast({ title: '未知策略类型', icon: 'none' })
	  }
	}


	function gotToDeviceControl(houseId) {
		uni.navigateTo({
			url: "/pages/control/deviceControl/deviceControl",
		});
	}

	function gotToStrategy(houseId) {
		uni.navigateTo({
			url: "/pages/control/deviceStrategy/deviceStrategy",
		});
	}
</script>

<style lang="scss" scoped>
	.controlLayout {
		.en-content {
			::v-deep .uni-section {
				background: transparent !important;
			}
		}

		.fer-content {
			::v-deep .uni-card {
				//控制卡片整体内边距
				padding-left: 0rpx !important;
				padding-right: 0rpx !important;
			}

			.title-row {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				padding-right: 30rpx;

				.history-title {
					color: #007AFF;
					font-size: 24rpx;
				}
			}

			.uni-card {

				.card-actions {
					display: flex;
					flex-direction: row;
					justify-content: space-around;
					align-items: center;
					height: 45px;
					border-top: 1px #eee solid;
				}

				.card-actions-item {
					display: flex;
					flex-direction: row;
					align-items: center;
				}

				.card-actions-item-text {
					font-size: 12px;
					color: #666;
					margin-left: 5px;
				}

				.device-card {
					// padding: 20rpx;
					border-radius: 10rpx;
					background-color: #efefef;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
					margin-bottom: 20rpx;
					overflow: hidden; // 避免溢出

					$row-actions-width: 220rpx;

					.row-track {
						height: 80rpx;
						display: flex;
						width: calc(100% + #{$row-actions-width});
						transform: translateX(0);
						transition: transform 0.25s ease;

						&.active {
							transform: translateX(-#{$row-actions-width});
						}

						.row-content {
							width: 100%;
							display: flex;
							justify-content: space-between;
							align-items: center;
							padding-left: 24rpx;
							padding-right: 40rpx;
						}

						.actions {
							width: $row-actions-width;
							height: 100%;
							display: flex;
							// justify-content: space-around;
							// align-items: center;

							.btn {
								width: 100rpx;
								height: 100%;
								font-size: 22rpx;
								color: #fff;
								display: flex;
								justify-content: center;
								align-items: center;

								&.control {
									background: #4caf50;
								}

								&.strategy {
									background: #2196f3;
								}
							}
						}
					}

					.device-status {
						font-size: 26rpx;
						font-weight: bold;

						&.running {
							color: #4cd964;
						}

						&.stopped {
							color: #999;
						}

						&.error {
							color: #ff3b30;
						}
					}
				}



			}

		}

		.cn-content {
			::v-deep .uni-card {
				//控制卡片整体内边距
				padding-left: 0rpx !important;
				padding-right: 0rpx !important;
			}

			.title-row {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				padding-right: 30rpx;

				.history-title {
					color: #007AFF;
					font-size: 24rpx;
				}
			}

			.uni-card {

				.last-control {
					margin-top: 20rpx;
					border: 1px solid #e5e5e5;
					border-radius: 8rpx;
					padding: 24rpx;
					background-color: #fff;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
				}

				.card-actions {
					display: flex;
					flex-direction: row;
					justify-content: space-around;
					align-items: center;
					height: 45px;
					border-top: 1px #eee solid;
				}

				.card-actions-item {
					display: flex;
					flex-direction: row;
					align-items: center;
				}

				.card-actions-item-text {
					font-size: 12px;
					color: #666;
					margin-left: 5px;
				}

			}
		}
	}
</style>